<template>
  <el-container style="height: 1000px; border: 1px solid #eee">
    <el-main>
      <router-view/>
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="form.name" placeholder="姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="咨询时间">
          <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              :value-format=valueFormat :format=format
              :disabled-date="disabledDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="filteredList.slice((currentPage-1)*pageSize,currentPage*pageSize)" style="font-size: 16px">
        <el-table-column type="index"
                         :index="indexFn"
                         prop="id"
                         label="No." width="100" align="center">
        </el-table-column>
        <el-table-column prop="id" width="1" align="center" v-if="false"></el-table-column>
        <el-table-column  prop="userAvatar" width="50" align="center">
          <template #default="scope" >
            <el-avatar :src="scope.row.userAvatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="咨询师" prop="name" width="300" align="center"></el-table-column>
        <el-table-column label="时长" prop="duration" width="180" align="center"></el-table-column>
        <el-table-column label="时间" prop="date" width="300" align="center"></el-table-column>
        <el-table-column label="评分" prop="rate" width="200" align="center">
          <template #default="scope" >
            <el-rate v-model="scope.row.rate" :allow-half="true"  disabled text-color="#ff9900"></el-rate>
          </template>
        </el-table-column>


        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-tooltip
                class="item"
                effect="light"
                content="聊天记录"
                placement="bottom"
            >
              <el-button icon="el-icon-search" circle @click="HandleDrawer(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip
                class="item"
                effect="light"
                content="导出记录"
                placement="bottom"
            >
              <el-button type="success" icon="el-icon-download" circle @click="recordDownload(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="filteredList.length"
          :page-size="pageSize"
          @current-change="paging"
      >
      </el-pagination>
      <el-drawer :title="drawerName" v-model="drawerVisible" :with-header="false">
        <span style="width: 150px"><el-button type="text" @click="getMoreMess(drawerName)">查看更多</el-button></span>
        <el-table id="eltable" :show-header="false" :data="mList" :height="800">
          <el-table-column prop="message" align="left" >
            <template #default="scope" >
              <span style="font-size: 12px;color:gray;font-weight: lighter" v-if="scope.row.message!==''">  {{scope.row.time}}</span>

              <el-row>
                <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" v-if="scope.row.message!==''"></el-avatar>
                &nbsp; &nbsp;
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-if="scope.row.message!=='' && scope.row.type === 'text'">
                  {{scope.row.message}}
                </el-card>
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-else-if="scope.row.message!==''  && scope.row.type === 'pic'">
                  <el-image :src="scope.row.message"></el-image>
                </el-card>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="mine">
            <template #default="scope" style="float: right">
              <el-row align="right" style="float: right">
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-if="scope.row.mine!==''  && scope.row.type === 'text'">
                  {{scope.row.mine}}
                </el-card>
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-else-if="scope.row.mine!==''  && scope.row.type === 'pic'">
                  <el-image :src="scope.row.mine"></el-image>
                </el-card>
                &nbsp; &nbsp;
                <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" v-if="scope.row.mine!==''"></el-avatar>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </el-main>
  </el-container>
</template>

<script>
import tim from "../../tim";
function offTime (value) {
  var v = value;
  var date = new Date(v * 1000);
  var Y = date.getFullYear() + "-";
  var M =
      (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
  var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var h =
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var m =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let dt = new Date(Date.parse(new Date()));
  let current = dt.getFullYear() + "-" + dt.getMonth() + "-" + dt.getDate();
  let system = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
  if (current === system) {
    return h + m;
  } else {
    return M + D;
  }
}
const circleUrl = 'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'
export default {
  name: "TutorRecord",
  data(){
    return{
      drawerVisible: false,
      drawerName: '',
      nextReqMessageID:'',
      isCompleted:false,
      mList:[],
      valueFormat:'YYYY-MM-DD',
      format:'YYYY-MM-DD',
      currentPage:1,
      pageSize:8,
      form:{
        name:'',
        date:''
      },
      disabledDate(time) {
        return time.getTime() > Date.now()
      },
      filteredList:[],
      dataList:[
        {
          name:'qwx124',
          userAvatar:circleUrl,
          duration:'01:12:23',
          date:'2022-03-18',
          rate:5,
          comment:'好',
          consultant:'qwx123'
        },
      ]
    }
  },
  methods: {
    HandleDrawer(name) {
      const _this = this
      _this.drawerVisible = true
      _this.drawerName = name
      _this.mList = []
      _this.nextReqMessageID = ''
      _this.isCompleted = false
      _this.getMess(15, name,'')
    },
    getMess(count, chatName, nextSeq) {
      const _this = this
      let promise2 = tim.getMessageList({
        conversationID: 'C2C' + chatName,
        nextReqMessageID:nextSeq,
        count: 15,
      });
      promise2.then(function (imResponse) {
        let tempList=[]
        for (const item of imResponse.data.messageList) {
          let m = ''
          let time = offTime(item.time)
          if (item.type === "TIMImageElem"){
            let m = item.payload.imageInfoArray[0].imageUrl
            if (item.from === String(chatName)) {
              tempList.push({time:time,message: m, mine: '',type:'pic'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'pic'})
            }
          }else{
            if (item.cloudCustomData === 'user') {
              m = '用户：\n '+item.payload.text
            } else if (item.cloudCustomData === 'consultant') {
              m = '咨询师：\n '+item.payload.text
            } else if (item.cloudCustomData === 'askhelp') {
              m = '----督导介入---- : '
            } else {
              m = item.payload.text
            }
            if (item.from === String(chatName)) {
              tempList.push({time:time,message: m, mine: '',type:'text'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'text'})
            }
          }
        }
        tempList = tempList.concat(_this.mList)
        _this.mList = tempList
        _this.nextReqMessageID = imResponse.data.nextReqMessageID
        _this.isCompleted = imResponse.data.isCompleted
        console.log(imResponse)
      });
    },
    getMoreMess(chatName){
      const _this = this
      if (_this.isCompleted===false){
        _this.getMess(15,chatName,_this.nextReqMessageID)
      }
    },
    async getMessForAll(chatName) {
      const _this = this
      let res = []
      let next = ''
      let nextSeq = ''
      let isCompl = false
      let cnt = 0
      while (isCompl===false){
        await tim.getMessageList({
          conversationID: 'C2C' + chatName,
          nextReqMessageID: nextSeq,
          count: 15,
        }).then(function (imResponse) {
          let tempList = []
          for (const item of imResponse.data.messageList) {
            let m = ''
            let time = offTime(item.time)
            if (item.type === "TIMImageElem"){
              let m = '[图片]'
              if (item.from === String(chatName)) {
                tempList.push({time:time,message: m, mine: '',type:'pic'})
              } else {
                tempList.push({time:time,message: '', mine: m,type:'pic'})
              }
            }else{
              if (item.cloudCustomData === 'user') {
                m = '用户：\n '+item.payload.text
              } else if (item.cloudCustomData === 'consultant') {
                m = '咨询师：\n '+item.payload.text
              } else if (item.cloudCustomData === 'askhelp') {
                m = '----督导介入---- : '
              } else {
                m = item.payload.text
              }
              if (item.from === String(chatName)) {
                tempList.push({message: m, mine: '',type:'text'})
              } else {
                tempList.push({message: '', mine: m,type:'text'})
              }
            }
          }
          tempList = tempList.concat(res)
          res = tempList
          nextSeq = imResponse.data.nextReqMessageID
          isCompl = imResponse.data.isCompleted
          console.log(res)
        })
      }
      console.log(res)
      return res
    },
    recordDownload(chatName){
      let res = []
      this.getMessForAll(chatName).then(data=>{
        res = data
        const downName = chatName+'_'+Math.floor(Math.random()*100000)
        let title = ['时间','用户'+chatName,'咨询师'+window.sessionStorage.getItem('username')]
        let key = ['time','message','mine']
        clickDownload(data,downName,title,key)
      })

    },
    paging(val){
      const _this = this
      _this.currentPage = val
    },
    onSubmit() {
      const _this = this
      _this.filteredList = _this.filterList(_this.form)
      console.log(this.form)
    },
    indexFn(index) {
      index = (index + 1) + (this.currentPage-1) * this.pageSize
      return index
    },
    filterList(item) {
      const _this = this
      let formList = {}
      let newList = []
      for(let key in item){
        if (item[key] !== ''){
          formList[key] = item[key]
        }
      }
      console.log(formList)
      if ((item.name === ''||item.name===null) && (item.date === ''||item.date===null)) {
        return _this.dataList
      }

      else {
        console.log(_this.dataList)
        let l = []
        l = _this.dataList
        for(let i = 0,len = l.length;i<len;++i){
          let flag = false
          //console.log(l[i])
          for(let keyy in formList){
            if (keyy === 'name'){//模糊匹配
              let str = '.*?'+formList['name']+'.*'
              let reg = new RegExp(str)
              if (reg.test(l[i]['name'])){

              }else{
                flag = true
              }
            }
            else{
              if(l[i][keyy] === formList[keyy]){
                // ...
              }
              else{
                flag = true
              }
            }
          }
          if (flag === false){
            newList.push(l[i])
          }
        }
        return newList
      }
    }
  },async created() {
    const _this = this
    let userId = window.sessionStorage.getItem('userid')
    let userSig = window.sessionStorage.getItem('usersig')
    await _this.$axios.get('http://106.14.247.163:8080/supervisor/getHelpRecords/' + userId).then(resp => {
      console.log(resp)
      _this.dataList = []
      for (let item of resp.data.data) {
        _this.dataList.push({
          id:item.consultant.userInfo.userId,
          name:item.consultant.userInfo.userName===null?'无':item.consultant.userInfo.userName,
          userAvatar: circleUrl,
          duration: item.recordInfo.duration === null ? 0 : item.recordInfo.duration,
          date: item.recordInfo.datetime === null ? '1970-01-01' : item.recordInfo.datetime.slice(0, 10),
          rate: 4
        })
      }
    })
    _this.filteredList = _this.dataList

    let promise = tim.login({userID: userId, userSig: userSig})
    promise.then((imResponse) => {
      console.log(imResponse.data);
    }).catch((imError) => {
      console.warn(imError)
    })

  },
  destroyed() {
    // 离开页面退出当前账号
    let promise = this.tim.logout();
    // promise
    //   .then(function (imResponse) {
    //     console.log(imResponse.data);
    //   })
    //   .catch(function (imError) {
    //     console.warn("logout error:", imError);
    //   });
  }
}
function clickDownload(data,fileName,title,key){
  JSonToCSV.setDataConver({
    data: data,
    fileName: fileName,
    columns: {
      title: title,//csv表头
      key: key,//json字段
      formatter: function(n, v) {
        if(n === 'avg_click_user_cnt') {
          return Number(v).toFixed(2);
        }
        if(v === undefined){
          return " ";
        }
      }
    }
  });
}
//csv下载
(function( global, factory ) {
  "use strict";
  if(typeof module === "object" && typeof module.exports === "object" ) {
    module.exports = global.document ?
        factory( global, true ) :
        function(w) {
          return factory(w);
        };
  } else {
    factory(global);
  }
})(window, function(){
  var JSonToCSV = {
    /*
     * obj是一个对象，其中包含有：
     * ## data 是导出的具体数据
     * ## fileName 是导出时保存的文件名称 是string格式
     * ## showLabel 表示是否显示表头 默认显示 是布尔格式
     * ## columns 是表头对象，且title和key必须一一对应，包含有
          title:[], // 表头展示的文字
          key:[], // 获取数据的Key
          formatter: function() // 自定义设置当前数据的 传入(key, value)
     */
    setDataConver: function(obj) {
      var bw = this.browser();
      if(bw['ie'] < 9) return; // IE9以下的
      var data = obj['data'],
          ShowLabel = typeof obj['showLabel'] === 'undefined' ? true : obj['showLabel'],
          fileName = (obj['fileName'] || 'UserExport') + '.csv',
          columns = obj['columns'] || {
            title: [],
            key: [],
            formatter: undefined
          };
      var ShowLabel = typeof ShowLabel === 'undefined' ? true : ShowLabel;
      var row = "", CSV = '', key;
      // 如果要现实表头文字
      if (ShowLabel) {
        // 如果有传入自定义的表头文字
        if (columns.title.length) {
          columns.title.map(function(n) {
            row += n + ',';
          });
        } else {
          // 如果没有，就直接取数据第一条的对象的属性
          for (key in data[0]) row += key + ',';
        }
        row = row.slice(0, -1); // 删除最后一个,号，即a,b, => a,b
        CSV += row + '\r\n'; // 添加换行符号
      }
      // 具体的数据处理
      data.map(function(n) {
        row = '';
        // 如果存在自定义key值
        if (columns.key.length) {
          columns.key.map(function(m) {
            row += '"' + (typeof columns.formatter === 'function' ? columns.formatter(m, n[m]) || n[m] : n[m]) + '",';
          });
        } else {
          for (key in n) {
            row += '"' + (typeof columns.formatter === 'function' ? columns.formatter(key, n[key]) || n[key] : n[key]) + '",';
          }
        }
        row.slice(0, row.length - 1); // 删除最后一个,
        CSV += row + '\r\n'; // 添加换行符号
      });
      if(!CSV) return;
      this.SaveAs(fileName, CSV);
    },
    SaveAs: function(fileName, csvData) {
      var bw = this.browser();
      if(!bw['edge'] && !bw['ie']) {
        var alink = document.createElement("a");
        alink.id = "linkDwnldLink";
        alink.href = this.getDownloadUrl(csvData);
        document.body.appendChild(alink);
        var linkDom = document.getElementById('linkDwnldLink');
        linkDom.setAttribute('download', fileName);
        linkDom.click();
        document.body.removeChild(linkDom);
      }
      else if(bw['ie'] >= 10 || bw['edge'] == 'edge') {
        var _utf = "\uFEFF";
        var _csvData = new Blob([_utf + csvData], {
          type: 'text/csv'
        });
        window.navigator.msSaveBlob(_csvData, fileName);
      }
      else {
        var oWin = window.top.open("about:blank", "_blank");
        oWin.document.write('sep=,\r\n' + csvData);
        oWin.document.close();
        oWin.document.execCommand('SaveAs', true, fileName);
        oWin.close();
      }
    },
    getDownloadUrl: function(csvData) {
      var _utf = "\uFEFF"; // 为了使Excel以utf-8的编码模式，同时也是解决中文乱码的问题
      if (window.Blob && window.URL && window.URL.createObjectURL) {
        var csvData = new Blob([_utf + csvData], {
          type: 'text/csv'
        });
        return URL.createObjectURL(csvData);
      }
      // return 'data:attachment/csv;charset=utf-8,' + _utf + encodeURIComponent(csvData);
    },
    browser: function() {
      var Sys = {};
      var ua = navigator.userAgent.toLowerCase();
      var s;
      (s = ua.indexOf('edge') !== - 1 ? Sys.edge = 'edge' : ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1]:
          (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
              (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                  (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                      (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                          (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
      return Sys;
    }
  };
  window.JSonToCSV = JSonToCSV;
});
</script>

<style scoped>
  #eltable{
    --el-table-border: 0px;
    --el-table-row-hover-background-color: none;
  }
</style>